package com.hymall.service.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hymall.bean.MarketKeyword;
import com.hymall.bean.MarketKeywordExample;
import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.CommonData;
import com.hymall.mapper.MarketKeywordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: 牟治宇
 * @description 关键词实现类
 * @date: 2022/7/18 12:30
 */
@Service
public class KeywordServiceImpl implements KeywordService {

    @Autowired
    MarketKeywordMapper marketKeywordMapper;

    @Override
    public MarketKeyword keywordCreate(MarketKeyword marketKeyword) {

        if (marketKeyword.getUrl() == null) {
            marketKeyword.setUrl("");
        }
        if (marketKeyword.getIsDefault() == null){
            marketKeyword.setIsDefault(false);
        }
        if (marketKeyword.getIsHot() == null){
            marketKeyword.setIsHot(false);
        }

        marketKeyword.setAddTime(new Date());
        marketKeyword.setUpdateTime(new Date());
        marketKeyword.setDeleted(false);
        marketKeyword.setSortOrder(100);
        int code = marketKeywordMapper.insert(marketKeyword);
        marketKeyword.setId(marketKeyword.getId());
        return marketKeyword;
    }

    @Override
    public MarketKeyword keywordUpdate(MarketKeyword keyword) {
        if (keyword.getUrl() == null) {
            keyword.setUrl("");
        }
        marketKeywordMapper.updateByPrimaryKey(keyword);
        return keyword;
    }

    @Override
    public int updateDelete(MarketKeyword marketKeyword) {
        Integer id = marketKeyword.getId();
        int code = marketKeywordMapper.keywordDelete(id);
        return code;
    }

    @Override
    public CommonData keywordList(String keyword, BasePageInfo basePageInfo, String url) {

        PageHelper.startPage(basePageInfo.getPage(),basePageInfo.getLimit());
        PageHelper.orderBy("update_time desc");

        MarketKeywordExample marketKeywordExample = new MarketKeywordExample();

        if (keyword != null) {
            marketKeywordExample.createCriteria().andKeywordLike("%" + keyword + "%");
        }
        if (url != null) {
            marketKeywordExample.createCriteria().andUrlLike("%" + url + "%");
        }
            marketKeywordExample.createCriteria().andDeletedEqualTo(false);
            List<MarketKeyword> marketKeywords = marketKeywordMapper.selectByExample(marketKeywordExample);

        PageInfo<MarketKeyword> marketKeywordPageInfo = new PageInfo<>(marketKeywords);
        return CommonData.data(marketKeywordPageInfo);
    }
}
